package com.filetransfer.view.Panel;
import com.filetransfer.config.UserThemeConfiguration;
import com.filetransfer.view.Components.MarkdownPanel;
import com.filetransfer.utils.SvgIconUtil;
import com.formdev.flatlaf.extras.FlatSVGIcon;
import de.exlll.configlib.YamlConfigurations;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import static com.filetransfer.Main.CONFIG_FILE_PATH;
public class MainPagePanel extends JPanel {
    private JScrollPane markdownContent;
    private final JButton floatingButton;
    private final JLayeredPane layeredPane;
    UserThemeConfiguration config = YamlConfigurations.update(CONFIG_FILE_PATH, UserThemeConfiguration.class);
    public MainPagePanel() {
        setLayout(new BorderLayout());
        MarkdownPanel markdownPanel = new MarkdownPanel();
        markdownContent = markdownPanel.createMarkdownPanel();
        layeredPane = new JLayeredPane();
        layeredPane.setLayout(null);
        add(layeredPane, BorderLayout.CENTER);
        layeredPane.add(markdownContent, JLayeredPane.DEFAULT_LAYER);
        markdownContent.setBounds(0, 0, 800, 600);
        FlatSVGIcon buttonIcon = SvgIconUtil.createSvgIcon("icons/gitcode2.svg", 30, 30);
        floatingButton = new JButton(buttonIcon);
        floatingButton.setPreferredSize(new Dimension(60, 60));
        floatingButton.putClientProperty("JButton.buttonType", "roundRect");
        floatingButton.setFont(floatingButton.getFont().deriveFont(16f));
        floatingButton.setBounds(700, 500, 60, 60);
        floatingButton.addActionListener(e -> openWebPage(config.getGitCode()));
        layeredPane.add(floatingButton, JLayeredPane.PALETTE_LAYER);
        addComponentListener(new java.awt.event.ComponentAdapter() {
            @Override
            public void componentResized(java.awt.event.ComponentEvent e) {
                Dimension size = getSize();
                markdownContent.setBounds(0, 0, size.width, size.height);
                int buttonSize = Math.min(size.width, size.height) / 10;
                floatingButton.setBounds(size.width - buttonSize - 20, size.height - buttonSize - 20, buttonSize, buttonSize);
            }
        });
    }
    @Override
    public void addNotify() {
        super.addNotify();
        resetScrollPosition();
    }
    private void resetScrollPosition() {
        if (markdownContent != null) {
            SwingUtilities.invokeLater(() -> markdownContent.getVerticalScrollBar().setValue(0));
        }
    }
    private void openWebPage(String url) {
        try {
            Desktop desktop = Desktop.getDesktop();
            desktop.browse(new URI(url));
        } catch (IOException | URISyntaxException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "无法打开网页: " + url, "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}